package org.qm.maven.plugin;

import com.sohu.thrift.generator.builder.ThriftFileBuilder;
import org.apache.maven.plugin.AbstractMojo;
import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugin.MojoFailureException;
import org.apache.maven.plugins.annotations.LifecyclePhase;
import org.apache.maven.plugins.annotations.Mojo;
import org.apache.maven.plugins.annotations.Parameter;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.HashSet;
import java.util.Set;

/**
 * @author daimao  Date: 15/9/18 Time: 上午11:31
 * @version $Id$
 */
@Mojo(name = "gen", defaultPhase = LifecyclePhase.INSTALL)
public class ThriftFileGenMojo extends AbstractMojo {

    @Parameter(property = "outputDir", defaultValue = "${project.build.directory}")
    private File outputDir;

    @Parameter(property = "classDir", defaultValue = "${project.build.outputDirectory}")
    private File classDir;

    @Parameter(required = true)
    private Set<String> basePackages;

    @Override
    public void execute() throws MojoExecutionException, MojoFailureException {

        Set<Class<?>> classes = new HashSet<>();

        for (String basePackage : basePackages) {
            try {
                Set<Class<?>> classesOfPackage = PackageUtils.getClasses(classDir, basePackage, getLog());
                classes.addAll(classesOfPackage);
            } catch (Exception e) {
                throw new MojoExecutionException("find classes error", e);
            }
        }

        File root = new File(outputDir.getAbsolutePath() + "/thrift-gen");
        if (root.exists()) {
            root.delete();
        }
        root.mkdir();

        String rootPath = root.getAbsolutePath();

        if (!classes.isEmpty()) {
            for (Class<?> clazz : classes) {
                FileOutputStream fos = null;
                try {

                    ThriftFileBuilder thriftFileBuilder = new ThriftFileBuilder();
                    File outPutFile = new File(rootPath + "/" + clazz.getSimpleName() + ".thrift");
                    fos = new FileOutputStream(outPutFile);
                    thriftFileBuilder.buildToOutputStream(clazz, fos);
                } catch (Exception e) {
                    throw new MojoExecutionException("building error", e);
                } finally {
                    if (fos != null) {
                        try {
                            fos.close();
                        } catch (IOException e) {
                            getLog().error("error close file");
                        }
                    }
                }
            }
        }

    }

}